#!/usr/bin/env python
# encoding: utf-8
'''
@author: ZhouXin
@time: 2018/6/13 0013 下午 17:43
'''

import jieba  # 分词包
import numpy
import codecs
import pandas
import matplotlib.pyplot as plot
from wordcloud import WordCloud

file = codecs.open(u'《梦里花落知多少》三毛.txt', 'r', encoding='gb18030')
content = file.read()
file.close()
segment = []
segs = jieba.cut(content)  # 切词
for seg in segs:
    if len(seg) > 1 and seg != '\r\n':
        segment.append(seg)
print(segment)
# 去停用词
words_df = pandas.DataFrame({'segment': segment})
words_df.head()
stopwords = pandas.read_csv("stopwords.txt", index_col=False, quoting=3, sep="\t", names=['stopword'], encoding='utf-8')
words_df = words_df[~words_df.segment.isin(stopwords.stopword)]

# 统计词频率
words_stat = words_df.groupby(by=['segment'])['segment'].agg({'计数': numpy.size})
words_stat = words_stat.reset_index()#.sort_values(columns="计数", ascending=False)

# %matplotlib inline
wordcloud = WordCloud(font_path="simhei.ttf", background_color="black")
r = words_stat.head(1000)
wordcloud = wordcloud.fit_words(dict(words_stat.head(7515).itertuples(index=False)))
plot.imshow(wordcloud)
plot.show()

#
# %matplotlib
wordcloud = WordCloud(font_path="simhei.ttf", background_color="black")
wordcloud = wordcloud.fit_words(dict(words_stat.head(1000).itertuples(index=False)))
plot.imshow(wordcloud)
plot.show()

from scipy.misc import imread
import matplotlib.pyplot as plt
from wordcloud import WordCloud, ImageColorGenerator

# %matplotlib inline
bimg = imread('bg_pic.png')
wordcloud = WordCloud(background_color="white", mask=bimg, font_path='simhei.ttf')
wordcloud = wordcloud.fit_words(dict(words_stat.head(4000).itertuples(index=False)))
bimgColors = ImageColorGenerator(bimg)
plt.axis("off")
plt.imshow(wordcloud.recolor(color_func=bimgColors))
plt.show()

# %matplotlib
bimg = imread('heart.jpeg')
wordcloud = WordCloud(background_color="white", mask=bimg, font_path='simhei.ttf')
wordcloud = wordcloud.fit_words(words_stat.head(39769).itertuples(index=False))
bimgColors = ImageColorGenerator(bimg)
plt.axis("off")
plt.imshow(wordcloud.recolor(color_func=bimgColors))
plt.show()
